package com.api.qfengx.data.doc;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import com.weaver.qfengx.*;
import weaver.file.ImageFileManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

@WebServlet("/qfengx/data/doc/down")
public class DocDownServlet extends HttpServlet {

    private static final LogUtils log = new LogUtils(DocDownServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> res = Maps.newHashMap();
        try {
            String docid = request.getParameter("docid");
            if (StringUtils.isEmpty(docid)) {
                res.put("code", "1");
                res.put("msg", "参数异常");
                respToJson(JSON.toJSONString(res), response);
                return;
            }

            ImageFileManager imageFileManager = ImageFileUtils.imageFileManager(docid);
            if (Objects.isNull(imageFileManager)) {
                res.put("code", "3");
                res.put("msg", "文件不存在");
                respToJson(JSON.toJSONString(res), response);
                return;
            }

            log.writeLog("===> 下载文件, name: " + imageFileManager.getImageFileName() + " , size: " + imageFileManager.getFilesize());
            String userAgent = request.getHeader("User-Agent");
            String filename = imageFileManager.getImageFileName();
            if (userAgent.toUpperCase().contains("MSIE") || userAgent.toUpperCase().contains("TRIDENT")) //针对IE或IE为内核的浏览器
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            else
                filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);//谷歌控制版本
            log.writeLog("===> 设置文件名");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            ByteStreams.copy(imageFileManager.getInputStream(), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", "-1");
            res.put("msg", "文件下载异常");
            respToJson(JSON.toJSONString(res), response);
        }
    }


    private void respToJson(Object object, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(new ObjectMapper().writeValueAsString(object));
    }


}
